<?php
/**
 * Created by PhpStorm.
 * User: 14775
 * Date: 2017/9/20
 * Time: 10:27
 */

namespace Common\ModelSQ;


class ERPUser extends ModelSQBase
{

    const CREATE_MEMBER = 'fzapi.crm.create_member';
    const UPDATE_MEMBER = 'fzapi.crm.update_member_info';
    const GET_MEMBER = 'fzapi.crm.member_info_get';
    const MEMBER_BONUS_SYNC = 'fzapi.crm.member_bonus_sync';
    const GET_MEMBER_BONUS = 'fzapi.crm.member_getbonusinfo';
    const GET_INTEGRAL_DEDUCTIONRULE = 'fzapi.crm.get_Integral_deductionrule';


    //创建会员
    public function createMember($member)
    {
        $result = $this->request(self::CREATE_MEMBER, json_encode($member));
        return json_decode($result, true);
    }

    //更新会员
    public function updateMember($member)
    {
        $this->request(self::UPDATE_MEMBER, json_encode($member));
        return true;
    }

    /**
     * 获取会员信息
     * @param $member array('member_code'=>'会员号','telephone'=>'手机号')
     * @return array
     */
    public function getMember($member)
    {
        $result = $this->request(self::GET_MEMBER, json_encode($member));
        return json_decode($result, true);
    }

    //会员积分同步
    public function memberBonusSync($bonus)
    {
        $this->request(self::GET_MEMBER, json_encode($bonus));
        return true;
    }


    /** 会员积分查询
     * @param $params array('')
     * @return array
     */
    public function getMemberBonus($params)
    {
        $this->request(self::GET_MEMBER_BONUS, json_encode($params));
        return array();
    }


    /**
     * 同步用户积分
     * @param $params
     * @return mixed
     */
    public function bonusSync($params)
    {
        $result = $this->request(self::MEMBER_BONUS_SYNC, json_encode($params));
        return json_decode($result, true);
    }

    /**
     * 获取积分抵扣规则
     * @param $params
     * @return mixed
     */
    public function getIntegralRule($params)
    {
        $result = $this->request(self::GET_INTEGRAL_DEDUCTIONRULE, json_encode($params));
        return json_decode($result, true);
    }

    private function request($method, $data)
    {
        $config = C('ERPUSER');
        $params = array(
            'app_id' => $config['APPID'],
            'apiSecret' => $config['ApiSecre'],
            'method' => $method,
            //   'format' => 'JSON',
            'charset' => 'utf-8',
            'sign_type' => 'md5',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0.0',
            'content' => $data,
        );

        ksort($params);

        $str_request_params = urldecode(http_build_query($params));

        $sign = md5($str_request_params);

        $params['sign'] = $sign;
        unset($params['apiSecret']);
        error_log('-------erp---------');
        error_log(print_r(urldecode(http_build_query($params)),1));
        $result = http_request($config['URL'], $params);
        error_log(print_r($result, 1));

        return $result;
    }
}